package org.csu.linkgame.controller;

import com.leewyatt.rxcontrols.controls.RXAudioSpectrum;
import com.leewyatt.rxcontrols.controls.RXLrcView;
import com.leewyatt.rxcontrols.controls.RXMediaProgressBar;
import com.leewyatt.rxcontrols.controls.RXToggleButton;
import com.leewyatt.rxcontrols.pojo.LrcDoc;
import com.leewyatt.rxcontrols.utils.RXResources;
import com.leewyatt.rxcontrols.utils.StyleUtil;
import de.felixroske.jfxsupport.FXMLController;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ToggleGroup;
import javafx.scene.effect.BoxBlur;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Shape;
import javafx.stage.FileChooser;
import javafx.stage.Window;
import javafx.util.Duration;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ResourceBundle;

@FXMLController
public class MusicViewController implements Initializable {
    @FXML
    public RXLrcView lrcPane;
    @FXML
    public RXAudioSpectrum spectrum;
    @FXML
    public RXMediaProgressBar progressBar;
    @FXML
    public ToggleGroup styleGroup;
    @FXML
    public RXToggleButton musicToggleButton;

    private FileChooser fileChooser = new FileChooser();

    private final String LRC_CODE = "UTF-8";

    private MediaPlayer player;

    private boolean isMusicStart = false;

    private boolean isMusicExist = false;
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        //实现切换样式功能
        String[] styleSheets = {
                RXResources.load("/org/csu/linkgame/css/spectrum_01.css").toExternalForm(),
                RXResources.load("/org/csu/linkgame/css/spectrum_02.css").toExternalForm(),
                RXResources.load("/org/csu/linkgame/css/spectrum_03.css").toExternalForm(),
                RXResources.load("/org/csu/linkgame/css/spectrum_04.css").toExternalForm(),
                RXResources.load("/org/csu/linkgame/css/spectrum_05.css").toExternalForm(),
                RXResources.load("/org/csu/linkgame/css/spectrum_06.css").toExternalForm()
        };
        BoxBlur barEffect = new BoxBlur(2.5,2.5,1);
        Shape shape = new Polygon(5,0,0,5,15,10,15,10);
        styleGroup.selectedToggleProperty().addListener((ob, ov, nv) ->{
            int index = styleGroup.getToggles().indexOf(nv);
            if(index==6){
                spectrum.setBarShape(shape);
            }else{
                spectrum.setBarShape(null);
            }
            if(index==0){
                StyleUtil.removeSheets(spectrum,styleSheets);
            }else {
                StyleUtil.toggleSheets(spectrum,styleSheets,styleSheets[index-1]);
            }
        });
    }

    public void openFileAction(ActionEvent event) {
        Window window = lrcPane.getScene().getWindow();
        File mp3File = fileChooser.showOpenDialog(window);
        if (mp3File != null) {
            isMusicExist = true;
            if(player!=null){
                player.dispose();
                lrcPane.setLrcDoc(null);
            }

            File dir = new File(mp3File.getParent());
            if (dir.isDirectory()) {
                fileChooser.setInitialDirectory(dir);
            }
            player = new MediaPlayer(new Media(mp3File.toURI().toString()));
            initProgressBar(player);
            initLrc(mp3File);
            initSpectrum(player);

            player.play();
        }
    }

    private void initSpectrum(MediaPlayer player) {
        player.setAudioSpectrumThreshold(-65);
        spectrum.audioSpectrumNumBandsProperty().bind(player.audioSpectrumNumBandsProperty());
        spectrum.audioSpectrumThresholdProperty().bind(player.audioSpectrumThresholdProperty());
        player.setAudioSpectrumListener((timestamp, duration, magnitudes, phases) -> {
            spectrum.setMagnitudes(magnitudes);
        });
    }

    private void initProgressBar(MediaPlayer player) {
        progressBar.setCurrentTime(Duration.ZERO);
        progressBar.durationProperty().bind(player.getMedia().durationProperty());
        progressBar.bufferProgressTimeProperty().bind(player.bufferProgressTimeProperty());
        player.currentTimeProperty().addListener((ob1, ov1, nv1) -> {
            progressBar.setCurrentTime(nv1);
        });

        progressBar.setOnMouseDragged(event1 -> {
            if ( player.getStatus() == MediaPlayer.Status.PLAYING) {
                player.seek(progressBar.getCurrentTime());
            }
        });

        progressBar.setOnMouseClicked(event1 -> {
            if (player.getStatus() == MediaPlayer.Status.PLAYING) {
                player.seek(progressBar.getCurrentTime());

            }
        });
    }

    private void initLrc(File file) {
        System.out.println(file);
        String lrcPath = file.getAbsolutePath().replaceAll("mp3$","lrc");
        System.out.println(lrcPath);
        File lrcFile = new File(lrcPath);
        if (lrcFile.exists()) {
            String lrc = "";
            try {

                lrc = new String(Files.readAllBytes(Paths.get(lrcPath)), LRC_CODE);
            } catch (IOException e) {
                e.printStackTrace();
            }
            lrcPane.setLrcDoc(LrcDoc.parseLrcDoc(lrc));
            lrcPane.currentTimeProperty().bind(player.currentTimeProperty());
        }
    }

    public void changeMusicStart(ActionEvent event) {
        if (isMusicExist) {
            if (musicToggleButton.isSelected()) {
//            player.stop();
                player.pause();
//            player.onPausedProperty().setValue(new Runnable());
                musicToggleButton.setText("播放");
            } else {
                player.play();
                musicToggleButton.setText("暂停");
            }
        }
    }
}
